/*
   Copyright 2010 Johan Hilding

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package org.johanhil.flygtider;

import java.util.List;

import org.johanhil.flygtider.flightwatch.FlightWatcher;
import org.johanhil.flygtider.provider.FetchFlights;
import org.johanhil.flygtider.provider.FlightInfo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the activity that shows detailed information about a flight.
 * ROADMAP:
 * * Display it in a more "listy" way, with nice icons/better headers.
 */
public class FlightInfoActivity extends Activity {
	FlightInfo flightInfo;
	FlightWatcher flightWatcher;
	TextView time;
	TextView airline;
	TextView notes;
	TextView flightNr;
	TextView arrivingAirport;
	TextView departingAirport;
	TextView terminal;
	CheckBox watch;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flightinfo);
        
        findViews();
        
        Bundle extras = getIntent().getExtras();
        
        // very basic error handling
        if (extras == null || ! extras.containsKey("flightinfo"))
        {
        	finish();
        }
        
        flightInfo = (FlightInfo) extras.get("flightinfo");
        
        // if the flight info was accessed from the search activity then
        // we need extra info.
        if (extras.getBoolean("refresh"))
        {
        	refreshData(flightInfo);
        }
        
        flightWatcher = new FlightWatcher(getApplicationContext());

        setText();
        
        setupListeners();
        
        if (flightWatcher.isWatched(flightInfo))
        {
        	watch.setChecked(true);
        }
    }
	
    @Override
    protected void onDestroy() {
        super.onDestroy();
        flightWatcher.close();
    }
    
    private void findViews()
    {
        time = (TextView) findViewById(R.id.time);
        airline = (TextView) findViewById(R.id.airline);
        notes = (TextView) findViewById(R.id.notes);
        flightNr = (TextView) findViewById(R.id.flightnr);
        arrivingAirport = (TextView) findViewById(R.id.arriving_airport);
        departingAirport = (TextView) findViewById(R.id.departing_airport);
        terminal = (TextView) findViewById(R.id.terminal);
        watch = (CheckBox) findViewById(R.id.watch_checkbox);
    }
    
    private void setText()
    {
        time.setText(flightInfo.getTime());
        airline.setText(flightInfo.getAirline());
        flightNr.setText(flightInfo.getFlightNr());
        arrivingAirport.setText(flightInfo.getArrivingAirport());
        departingAirport.setText(flightInfo.getDepartingAirport());
        notes.setText(flightInfo.getNotes());
        
        // some airports have terminals, others don't.
        if (flightInfo.getTerminal() != null)
        {
        	terminal.setText(flightInfo.getTerminal());
        }
        else
        {
        	findViewById(R.id.terminalLayout).setVisibility(View.GONE);
        }
    }
    
    private void setupListeners()
    {
        
        watch.setOnClickListener(new OnClickListener() {
        	public void onClick(View v)
        	{
        		if (watch.isChecked())
        		{
        			flightWatcher.add(flightInfo);
        			Toast.makeText(FlightInfoActivity.this, R.string.watch_started, Toast.LENGTH_SHORT).show();
        		}
        		else
        		{
        			flightWatcher.remove(flightInfo);
        			Toast.makeText(FlightInfoActivity.this, R.string.watch_stopped, Toast.LENGTH_SHORT).show();
        		}
        	}
        }
        		
        
        );
    }
    
    private void refreshData(FlightInfo oldData)
    {
    	FetchFlights fetchFlightsTask = new FetchFlights(this, R.string.loading_flight,
                new FetchFlights.ResultHandler()
                {
    	    // TODO MAJOR CODE DUPLICATION FROM LFVFlightSearch.getFlight().
    	    // stuff this in a filter that the "Sök" in FlightListActivity will
    	    // use aswell.
                    public void handleResult(List<FlightInfo> result)
                    {
                        for (FlightInfo flight : result)
                        {
                            if (flightInfo.getDate().equals(flight.getDate()))
                            {
                                flightInfo = flight;
                            }
                        }

                        setText();

                    }
                });

        fetchFlightsTask.execute(flightInfo.getIdentifyingAirport(), flightInfo.isArriving(), flightInfo.getFlightNr());
    }
    
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.flightinfoactivity_options, menu);
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		// there's only one option so we don't need any logic.
		refreshData(flightInfo);
		Toast.makeText(this, R.string.refresh_successful, Toast.LENGTH_SHORT);
		return true;
	}
}
